﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using WinBookKeeping.Utility;
using WinBookKeeping.Data;
using WinBookKeeping.Models;
using System.Speech.Recognition;
using System.Speech.Synthesis;

namespace WinBookKeeping
{
    public partial class FrmItemManage : Form
    {
        private readonly IBookKeepingRepository _repository;
        private int actType = 1;//提交状态 1 新增 2 修改
        private int selIndex = -1;
        private Dictionary<int, string> itemList = new Dictionary<int, string>();
        private SpeechRecognitionEngine recognizer;
        private SpeechSynthesizer synthesizer;
        private bool isListening = false;
        private TextBox currentTargetTextBox;

        public FrmItemManage()
        {
            InitializeComponent();
            _repository = new BookKeepingRepository();
            InitializeSpeechRecognition();
        }

        private void InitializeSpeechRecognition()
        {
            try
            {
                recognizer = new SpeechRecognitionEngine();
                synthesizer = new SpeechSynthesizer();

                // 创建语法
                var grammar = new GrammarBuilder();
                grammar.AppendDictation();
                recognizer.LoadGrammar(new Grammar(grammar));

                // 设置事件处理
                recognizer.SpeechRecognized += Recognizer_SpeechRecognized;
                recognizer.SpeechRecognitionRejected += Recognizer_SpeechRecognitionRejected;

                // 设置输入设备
                recognizer.SetInputToDefaultAudioDevice();
            }
            catch (Exception ex)
            {
                MessageHelper.Error("语音识别初始化", $"初始化语音识别失败：{ex.Message}");
            }
        }

        private void Recognizer_SpeechRecognized(object sender, SpeechRecognizedEventArgs e)
        {
            if (e.Result.Confidence > 0.7 && currentTargetTextBox != null)
            {
                string recognizedText = e.Result.Text;
                if (currentTargetTextBox == textItemId)
                {
                    if (int.TryParse(recognizedText, out int id))
                    {
                        currentTargetTextBox.Text = id.ToString();
                    }
                }
                else
                {
                    currentTargetTextBox.Text = recognizedText;
                }
                StopVoiceInput();
            }
        }

        private void Recognizer_SpeechRecognitionRejected(object sender, SpeechRecognitionRejectedEventArgs e)
        {
            synthesizer.SpeakAsync("抱歉，我没有听清楚，请重试。");
            StopVoiceInput();
        }

        private void StartVoiceInput(TextBox targetTextBox)
        {
            if (!isListening)
            {
                try
                {
                    currentTargetTextBox = targetTextBox;
                    recognizer.RecognizeAsync(RecognizeMode.Single);
                    isListening = true;
                    synthesizer.SpeakAsync("请说话。");
                }
                catch (Exception ex)
                {
                    MessageHelper.Error("语音输入", $"启动语音输入失败：{ex.Message}");
                }
            }
        }

        private void StopVoiceInput()
        {
            if (isListening)
            {
                recognizer.RecognizeAsyncStop();
                isListening = false;
                currentTargetTextBox = null;
            }
        }

        private void btnVoiceInputId_Click(object sender, EventArgs e)
        {
            StartVoiceInput(textItemId);
        }

        private void btnVoiceInputName_Click(object sender, EventArgs e)
        {
            StartVoiceInput(textItemName);
        }

        protected override void OnFormClosing(FormClosingEventArgs e)
        {
            base.OnFormClosing(e);
            if (recognizer != null)
            {
                recognizer.Dispose();
            }
            if (synthesizer != null)
            {
                synthesizer.Dispose();
            }
        }

        private async void FrmItemManage_Load(object sender, EventArgs e)
        {
            cboTypes.SelectedIndex = 0;
            actType = 1;
            listBox1.Items.Clear();
            await LoadItemList();
        }

        private async Task LoadItemList()
        {
            listBox1.Items.Clear();
            itemList.Clear();
            var items = await _repository.GetAllItemsAsync();
            foreach (var item in items)
            {
                string displayText = $"{item.Id}                 {item.ItemType}                 {item.ItemName}";
                listBox1.Items.Add(displayText);
                itemList.Add(item.Id, $"{item.Id};{item.ItemType};{item.ItemName}");
            }
        }

        private async void btnOk_Click(object sender, EventArgs e)
        {
            int id = 0;
            if (!string.IsNullOrEmpty(textItemId.Text))
            {
                id = Convert.ToInt32(textItemId.Text.Trim());
            }
            string type = cboTypes.Text.Trim();
            string itemName = textItemName.Text.Trim();

            if (id == 0)
            {
                MessageHelper.Error("名目提交", "名目编号不能为空！");
                textItemId.Focus();
                return;
            }
            else if (actType == 1 && itemList.ContainsKey(id))
            {
                MessageHelper.Error("名目提交", "名目编号已存在！");
                textItemId.Focus();
                return;
            }
            if (string.IsNullOrEmpty(itemName))
            {
                MessageHelper.Error("名目提交", "名目名称不能为空！");
                textItemName.Focus();
                return;
            }
            else if (actType == 1 && await ExistItemName(itemName))
            {
                MessageHelper.Error("名目提交", "名目名称已存在！");
                textItemName.Focus();
                return;
            }

            try
            {
                var item = new RecordInfo
                {
                    Id = id,
                    ItemType = type,
                    ItemName = itemName,
                    Description = "",
                    Money = 0,
                    RecordTime = DateTime.Now
                };

                if (actType == 1)
                {
                    await _repository.AddItemAsync(item);
                    string displayText = $"{id}                 {type}                 {itemName}";
                    listBox1.Items.Add(displayText);
                    itemList.Add(id, $"{id};{type};{itemName}");
                }
                else
                {
                    await _repository.UpdateItemAsync(item);
                    string displayText = $"{id}                 {type}                 {itemName}";
                    listBox1.Items.Insert(selIndex, displayText);
                    listBox1.Items.RemoveAt(selIndex + 1);
                    itemList[id] = $"{id};{type};{itemName}";
                }
                MessageHelper.Info("名目提交", "保存成功！");
                await LoadItemList();
            }
            catch (Exception ex)
            {
                MessageHelper.Error("名目提交", $"保存失败：{ex.Message}");
            }
        }

        private async Task<bool> ExistItemName(string name)
        {
            var items = await _repository.GetAllItemsAsync();
            return items.Any(i => i.ItemName == name);
        }

        private void btnClear_Click(object sender, EventArgs e)
        {
            ClearInfo();
        }

        private void ClearInfo()
        {
            textItemId.Text = "";
            cboTypes.SelectedIndex = 0;
            textItemName.Text = "";
            textItemId.Enabled = true;
            btnOk.Text = "新增";
            actType = 1;
        }

        private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (listBox1.SelectedItems.Count > 0)
            {
                string selItem = listBox1.SelectedItems[0].ToString();
                int id = int.Parse(selItem.Split(new[] { "                 " }, StringSplitOptions.None)[0]);
                string strItem = itemList[id];
                string[] currentItem = strItem.Split(';');
                textItemId.Text = currentItem[0];
                textItemName.Text = currentItem[2];
                cboTypes.Text = currentItem[1];
                textItemId.Enabled = false;
                actType = 2;
                btnOk.Text = "修改";
                selIndex = listBox1.SelectedIndices[0];
            }
        }

        private async void btnDelete_Click(object sender, EventArgs e)
        {
            var selList = listBox1.SelectedItems;
            if (selList.Count > 0)
            {
                DialogResult dr = MessageHelper.Confirm("删除名目", "你确定要删除该名目信息吗？");
                if (dr == DialogResult.OK)
                {
                    try
                    {
                        foreach (string item in selList)
                        {
                            int id = int.Parse(item.Split(new[] { "                 " }, StringSplitOptions.None)[0]);
                            await _repository.DeleteItemAsync(id);
                        }
                        await LoadItemList();
                        MessageHelper.Info("删除名目", "删除成功!");
                    }
                    catch (Exception ex)
                    {
                        MessageHelper.Error("删除名目", $"删除失败：{ex.Message}");
                    }
                }
            }
        }
    }
}
